package com.lb.mybatis.core;


import com.lb.bean.User;
import org.apache.commons.math3.fitting.leastsquares.ParameterValidator;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Proxy;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName： MapperProxyFactory
 * @Description：
 * @Author: 蓝莲花
 * @Date： 2024/1/13 21:18
 * @Version： V1.0
 */
public class MapperProxyFactory {

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static <T> T getMapper(Class<T> mapper) {
        Object proxyInstance = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{mapper}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                Connection connection = getConnection();

                Select annotation = method.getAnnotation(Select.class);
                String sql = annotation.value();
                System.out.println(sql);

                Map<String, Object> paramValueMapping = new HashMap<>();
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    paramValueMapping.put(parameter.getName(), args[i]);
                }

                PreparedStatement statement = connection.prepareStatement("select * from user where name = ?");
                statement.setString(1, "lisi");

                statement.execute();

                ResultSet resultSet = statement.getResultSet();
                List<User> list = new ArrayList<>();

                while (resultSet.next()) {
                    User user = new User();
                    user.setId(resultSet.getInt("id"));
                    user.setName(resultSet.getString("name"));
                    user.setAge(resultSet.getInt("age"));
                    list.add(user);
                }

                list.forEach(System.out::println);

                return null;
            }
        });
        return (T) proxyInstance;
    }

    private static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_test?useUnicode=true&characterEncoding=utf8&useSSL=false",
                "root","123456abcd@");
        return connection;
    }

}
